import { ModalConfirm, TableLayout } from '@/components';
import {
  patientDischarged,
  patientList,
  patientRemove,
} from '@/services/patientMsg';
import {
  PageContainer,
  ProFormSelect,
  ProFormText,
} from '@ant-design/pro-components';
import { history } from '@umijs/max';
import { Breadcrumb, Button, message } from 'antd';
import { stringify } from 'querystring';
import React, { useRef, useState } from 'react';
import { NavLink } from 'react-router-dom';
import ItemOption from './ItemOption';

const DeviceList = React.forwardRef((props: any, ref) => {
  const { from, getChildrenSelectData, ecgModuleItem } = props;
  const tableLayoutRef = useRef<any>(null);
  const [modItem, setModItem] = useState<any>({});
  const modalConfirmRef = useRef<any>(null);
  const itemOptionRef = useRef<any>(null);
  const [paginationTotal, setPaginationTotal] = useState(0);
  const [selectedKeys, setSelectedKeys] = useState<any>([]);
  const rowSelection = {
    type: 'radio',
    fixed: 'left',
    selectedRowKeys: selectedKeys,
    onChange: (keys: any, rows: any) => {
      setSelectedKeys(keys);
      getChildrenSelectData && getChildrenSelectData('patient', keys); // 调用父组件的方法，传递选中的数据
    },
  };
  const getTableData = async (params?: any) => {
    const res = await patientList(params);
    if (res?.code === 200) {
      setPaginationTotal(res.total);
      if (from === 'components' && selectedKeys.length === 0) {
        if (ecgModuleItem?.patient?.id) {
          setSelectedKeys([ecgModuleItem?.patient?.id]);
          getChildrenSelectData &&
            getChildrenSelectData('patient', [ecgModuleItem?.patient?.id]);
        } else {
          if (res.rows.length > 0) {
            setSelectedKeys([res.rows[0].id]);
            getChildrenSelectData &&
              getChildrenSelectData('patient', [res.rows[0].id]); // 调用父组件的方法，传递选中的数据
          }
        }
      }
      return res.rows;
    }
    return [];
  };
  const columns: any = [
    // 搜索
    {
      dataIndex: 'name',
      hideInTable: true,
      renderFormItem: () => {
        return (
          <ProFormText
            label="患者名称"
            placeholder="患者名称"
            fieldProps={{
              maxLength: 200,
            }}
          />
        );
      },
    },
    {
      dataIndex: 'phone',
      hideInTable: true,
      hideInSearch: from === 'components' ? true : false, // 组件不显示
      renderFormItem: () => {
        return (
          <ProFormText
            label="患者手机号"
            placeholder="患者手机号"
            fieldProps={{
              maxLength: 200,
            }}
          />
        );
      },
    },
    {
      dataIndex: 'areaBinded',
      hideInTable: true,
      initialValue: from === 'components' ? '1' : null, // 组件不显示
      renderFormItem: () => {
        return (
          <ProFormSelect
            label="是否绑定分区"
            placeholder="是否绑定分区"
            options={[
              { label: '请选择', value: null },
              { label: '已绑定分区', value: '1' },
              { label: '未绑定分区', value: '0' },
            ]}
          />
        );
      },
    },
    // 表格
    {
      title: '名称',
      dataIndex: 'name',
      hideInSearch: true,
    },
    {
      title: '性别',
      dataIndex: 'sex',
      hideInSearch: true,
      width: 80,
      render: (_: any, record: any) => (
        <div>{record.sex == 1 ? '男' : record.sex == 2 ? '女' : '-'}</div>
      ),
    },
    {
      title: '患者手机号',
      dataIndex: 'phone',
      hideInSearch: true,
      width: 140,
      hideInTable: from === 'components' ? true : false, // 组件不显示
    },
    {
      title: '血型',
      dataIndex: 'blood',
      hideInSearch: true,
      hideInTable: from === 'components' ? true : false, // 组件不显示
      width: 80,
      render: (_: any, record: any) => (
        <div>
          {record.blood == 1 && 'A型'}
          {record.blood == 2 && 'B型'}
          {record.blood == 3 && 'AB型'}
          {record.blood == 4 && 'O型'}
          {record.blood == 5 && 'RH型'}
        </div>
      ),
    },
    {
      title: '床位',
      dataIndex: 'bedNo',
      hideInSearch: true,
      render: (_: any, record: any) => (
        <div>
          {record?.ward?.name}
          {record?.ward?.bed?.code ? '/' + record?.ward?.bed?.code : '-'}
        </div>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      hideInSearch: true,
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      width: from !== 'components' ? 220 : 150,
      fixed: 'right',
      render: (_: any, record: any) => (
        <div className="custom-table-option">
          {from !== 'components' && (
            <a onClick={() => handleOption(record, 'patientLimit')}>
              报警限详情
            </a>
          )}
          <a onClick={() => handleOption(record, 'edit')}>修改</a>
          <a onClick={() => handleOption(record, 'leave')}>出院</a>
          {/* <a className="danger" onClick={() => handleOption(record, 'delete')}>
            删除
          </a> */}
        </div>
      ),
    },
  ];
  // 删除操作
  const handleDelete = async () => {
    const res = await patientRemove({
      id: modItem?.id || 0,
    });
    if (res?.code === 200) {
      message.success('操作成功');
      modalConfirmRef?.current?.handleModalShow();
      refreshList();
    }
  };
  // 患者离院操作
  const handleLeave = async () => {
    const res = await patientDischarged({
      patientId: modItem?.id || 0,
    });
    if (res?.code === 200) {
      message.success('操作成功');
      modalConfirmRef?.current?.handleModalShow();
      refreshList();
    }
  };
  // 操作栏操作
  const handleOption = (row: any, key: string) => {
    setModItem({
      ...row,
      modKey: key,
    });
    if (key === 'delete') {
      modalConfirmRef?.current?.handleModalShow('是否删除该患者?');
    } else if (key === 'edit') {
      itemOptionRef?.current?.handleModalShow(row);
    } else if (key === 'patientLimit') {
      history.push({
        pathname: '/patientMsg/patientLimit',
        search: stringify({
          patientId: row.id,
        }),
      });
    } else if (key === 'leave') {
      modalConfirmRef?.current?.handleModalShow('该患者确定出院?');
    }
  };
  const modalSuccessCallback = () => {
    if (modItem.modKey === 'delete') {
      handleDelete();
    } else if (modItem.modKey === 'leave') {
      handleLeave();
    }
  };
  const refreshList = () => {
    tableLayoutRef?.current?.tableReload();
  };
  return (
    <PageContainer
      header={{
        title: <></>,
        ghost: true,
        breadcrumbRender: (route: any) => {
          return (
            <Breadcrumb
              items={[
                {
                  title: (
                    <div
                      style={{
                        display: 'flex',
                        alignContent: 'center',
                      }}
                    >
                      <NavLink to="/patientMsg">患者管理</NavLink>
                      <div
                        className="ant-breadcrumb-separator"
                        aria-hidden="true"
                      >
                        /
                      </div>
                      <div>患者列表</div>
                    </div>
                  ),
                },
              ]}
            ></Breadcrumb>
          );
        },
      }}
    >
      <TableLayout
        ref={tableLayoutRef}
        getTableData={getTableData}
        headerTitle="患者管理"
        rowSelection={from === 'components' ? rowSelection : false}
        toolBarRender={() => (
          <>
            <Button
              className="base-button"
              type="primary"
              onClick={() => itemOptionRef?.current?.handleModalShow()}
            >
              新增患者
            </Button>
          </>
        )}
        columns={columns}
        rowKey={'id'}
        scrolly={from !== 'components' ? 'auto' : '380px'}
        pagination={{
          total: paginationTotal,
        }}
      />
      {/* 确认弹层 */}
      <ModalConfirm
        ref={modalConfirmRef}
        successCallback={modalSuccessCallback}
      />
      {/* 添加编辑弹层 */}
      <ItemOption ref={itemOptionRef} refreshList={refreshList} />
    </PageContainer>
  );
});

export default DeviceList;
